
let baseURL = 'http://127.0.0.1:6789'; // 动态配置的baseURL
let tagNameList:Array<string> = ["紫外","红外","温度","湿度","压力"] // 报警的模块类型
const lastAlarmTimeMap = new Map(); // 设备ID->上次报警时间戳

self.onmessage = async (e) => {
    let msg = e.data;
    console.log('接收到端口配置消息==========')
    console.log(msg)
    // 处理端口配置消息
    if (msg.type === 'set_port' && msg.host) {
        baseURL = msg.host
        return;
    }
    
    let level, data, module_id, type, info, gateway_ip, gateway_name, custom_name;
    if (msg.type === 'save_error_info' && msg.data) {
      // 新结构
      const record = msg.data.alarmRecord || msg.data.clearRecord || msg.data;
      level = record.level || 0;
      data = record.actualValue;
      module_id = record.deviceId;
      type = record.sensorIndex;
      info = record.info;
      gateway_ip = record.gatewayIp;
      gateway_name = record.gatewayName;
      custom_name = record.customName; // 自定义名称
      // 性能优化：同一网关下同一设备30秒内只统计一次报警
      const now = Date.now();
      const key = `${gateway_ip}_${module_id}_${type}`;
      if (level === 'error') { // 只对报警生效
        const lastTime = lastAlarmTimeMap.get(key);
        if (lastTime && now - lastTime < 30000) {
          // 30秒内重复报警，直接忽略
          return;
        }
        lastAlarmTimeMap.set(key, now);
      }
    } 
    // 发送请求
    try {
      await fetch(baseURL + "/admin/addErrorRecord", {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          date:  new Date().toLocaleDateString().replace(/\//g,'-'),
          module_id,
          state: 0,
          level,
          info,
          type_id: type,
          error_value: data,
          gateway_ip,
          gateway_name,
          device_name: custom_name || `监测点${module_id}` // 如果没有自定义名称则使用默认格式
        })
        })
    } catch (err) {
      // 可选：postMessage 通知主线程错误
     console.log("出现错误")
    }
}

// 定期清理Map，移除30秒前的key，防止内存溢出
setInterval(() => {
  const now = Date.now();
  for (const [key, lastTime] of lastAlarmTimeMap.entries()) {
    if (now - lastTime > 30000) {
      lastAlarmTimeMap.delete(key);
    }
  }
}, 5 * 60 * 1000); // 每5分钟清理一次